package io.gitee.zhangbinhub.admin.adminserver.conf

import de.codecentric.boot.admin.server.config.AdminServerProperties
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.Customizer
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.web.SecurityFilterChain
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler
import org.springframework.security.web.util.matcher.AntPathRequestMatcher

@Configuration
class AdminServerAutoConfiguration @Autowired
constructor(adminServerProperties: AdminServerProperties) {
    private val adminContextPath: String = adminServerProperties.contextPath

    /**
     * http 验证策略配置
     *
     * @param http http 安全验证对象
     * @throws Exception 异常
     */
    @Bean
    @Throws(Exception::class)
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        val successHandler = SavedRequestAwareAuthenticationSuccessHandler()
        successHandler.setTargetUrlParameter("redirectTo")
        successHandler.setDefaultTargetUrl("$adminContextPath/")
        return http.csrf { it.disable() }.authorizeHttpRequests { authorize ->
            authorize.requestMatchers(
                AntPathRequestMatcher("$adminContextPath/assets/**"),
                AntPathRequestMatcher("$adminContextPath/instances"),
                AntPathRequestMatcher("$adminContextPath/instances/**"),
                AntPathRequestMatcher("$adminContextPath/login"),
                AntPathRequestMatcher("$adminContextPath/error"),
                AntPathRequestMatcher("$adminContextPath/webjars/**"),
                AntPathRequestMatcher("$adminContextPath/notifications/**"),
                AntPathRequestMatcher("$adminContextPath/proxy.stream")
            ).permitAll().anyRequest().authenticated()
        }.httpBasic(Customizer.withDefaults())
            .formLogin { it.loginPage("$adminContextPath/login").successHandler(successHandler) }
            .logout { it.logoutUrl("$adminContextPath/logout") }.build()
    }
}